import { Message } from "@arco-design/web-vue";
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import axios from "axios";

// 拦截器
export interface HttpResponse<T = unknown> {
  status: number;
  msg: string;
  code: number;
  data: T;
}

if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

axios.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 在拦截器中添加Token信息
    config.headers.Authorization = `Bearer ${sessionStorage.getItem("token")}`;
    //30秒超时
    config.timeout = 30 * 1000 ;
    config.timeoutErrorMessage = "接口超时";
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
axios.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    const res = response.data;
    if (response.status == 401) {
      Message.error({
        content: "无效的会话，或者会话已过期，请重新登录。",
        duration: 5 * 1000,
      });
      return;
    }
    if(response.config.responseType ===  'blob' || response.config.responseType ===  'arraybuffer'){
      return response.data;
    }
    if (res.code !== 200) {
      if (res.code == 401) {
        Message.error({
          content: "无效的会话，或者会话已过期，请重新登录。",
          duration: 5 * 1000,
        });
        return;
      } else {
        Message.error({
          content: res.msg || "系统未知错误，请反馈给管理员",
          duration: 5 * 1000,
        });
        return Promise.reject(
          new Error(res.msg || "系统未知错误，请反馈给管理员")
        );
      }
    }

    return res;
  },
  (error) => {
    Message.error({
      content: error.msg || "后端接口异常",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);
